import { Injectable } from "@angular/core";
import { BehaviorSubject, Observable } from "rxjs";
const Stomp = require("stompjs");
import { environment } from "@environment/environment";

@Injectable({
  providedIn: "root"
})
export class SkService {
  private socket: any;
  connected$ = new BehaviorSubject<boolean>(false);

  constructor() {
    this.init();
  }

  init() {
    this.socket = Stomp.over(
      new WebSocket(
        `${environment.protoWs}${environment.host.ws}/endpointService/websocket`
      )
      // new WebSocket(
      //   `${environment.protoWs}${
      //     environment.host.napi
      //   }/endpointService/websocket`
      // )
    );
    // new WebSocket("ws://napi.zqd.com/endpointService/websocket")
    // new WebSocket("ws://napi.zqd.com/endpointService/websocket")
    this.socket.debug = null;
    this.addListen();
  }

  disconnect() {
    this.socket.disconnect();
  }

  sub(url: string) {
    return new Observable(observer => {
      this.socket.subscribe(url, (data: any) => {
        observer.next(data);
      });

      // dispose of the event listener when unsubscribed
      return () => this.socket.unsubscribe(url);
    });
  }

  addListen() {
    this.socket.connect(
      {},
      () => {
        this.connected$.next(true);
      }
    );
  }
}

// this.sub("/quote/quote.ETHBTC.tradingview.60").subscribe(e => {
//   console.log(e, 999999);
// });
